package cn.schoolwow.quickdao.module.database.ddl.action.service.table;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteUpdateConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class BackupTableFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        String tableName = (String) flowContext.checkData("tableName");
        String backupTableName = (String) flowContext.checkData("backupTableName");

        DatabaseProvider databaseProvider = quickDAOConfig.databaseContext.databaseProvider;

        switch (databaseType){
            case SQLite:{
                flowContext.putTemporaryData("sql", "create table "+databaseProvider.escape(backupTableName)+"" +
                        " as select * from "+databaseProvider.escape(tableName)+";");
            }break;
            case Mysql:
            case MariaDB:{
                flowContext.putTemporaryData("sql", "create table "+databaseProvider.escape(backupTableName) +
                        " as select * from "+databaseProvider.escape(tableName)+";");
            }break;
            case Postgresql:{
                flowContext.putTemporaryData("sql", "select * into "+databaseProvider.escape(backupTableName)+" from "+databaseProvider.escape(tableName)+";");
            }break;
            default:{
                throw new UnsupportedOperationException("当前不支持"+databaseType.name()+"数据库备份表功能");
            }
        }

        flowContext.startFlow(new ExecuteUpdateConnectionFlow())
                .putTemporaryData("name", "备份表")
                .execute();
    }

    @Override
    public String name() {
        return "备份表";
    }
}
